package smqzqglpt;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.sql.*;

public class SynchronousElectronicContract {

    // 数据库配置
    private static final String DB_URL = "jdbc:mysql://localhost:3306/xiangmuzhikong?useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";

    public static void main(String[] args) {
        List<File> files = FileUtil.loopFiles("D:\\document\\预算及项目全生命周期质控平台\\电子合同");

        List<String> error = new ArrayList<>();
        List<String> success = new ArrayList<>();
        files.forEach(file -> {
            System.out.println(file.getName());
            String fileName = file.getName();

            // 1. 移除文件扩展名（如.pdf）
            String nameWithoutExt = fileName.replaceAll("\\.\\w+$", "");
            // 2. 提取括号或空格前的内容
            String[] parts = nameWithoutExt.split("[（(\\s]"); // 匹配中文括号、英文括号或空格
            String xuhao = parts[0].trim();
            queryContractFromDB(xuhao, null, file, error, success);

//            // 从文件名中提取序号和合同编号
//            String[] parts = fileName.split("\\s+|\\(|\\)|\\."); // 按空格、括号、点号分割
//            if (parts.length >= 3) {
//                String xuhao = parts[0].trim();
//                String hetongbianhao = parts[2].trim();
//
//                System.out.println("序号: " + xuhao);
//                System.out.println("合同编号: " + hetongbianhao);
//
//                // 查询数据库
//                queryContractFromDB(xuhao, hetongbianhao, file, error, success);
//            }
        });


        String outputPath = "./电子合同同步数据库信息";
        FileUtil.writeUtf8Lines(error, FileUtil.file(outputPath + ".error.txt"));
        FileUtil.writeUtf8Lines(success, FileUtil.file(outputPath + ".success.txt"));

        System.out.println("同步电子合同");
    }

    private static void queryContractFromDB(String xuhao, String hetongbianhao, File file, List<String> error, List<String> success) {
        try {
            // 显式加载驱动（可选）
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 获取连接
            Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            System.out.println("数据库连接成功！");
//            String sql = "SELECT * FROM citic_contract WHERE xuhao = ? AND hetongbianhao = ?";
            String sql = "SELECT * FROM citic_contract WHERE xuhao = ?";
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, xuhao);
//            preparedStatement.setString(2, hetongbianhao);

            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                System.out.println("找到匹配的合同记录:");
                System.out.println("ID: " + resultSet.getString("id"));
                System.out.println("合同名称: " + resultSet.getString("hetongmingcheng"));
                //添加合同记录
                insertFileInfo(file, resultSet.getString("id"));

                // TODO: 根据业务需求处理文件和数据
                success.add(file.getName() + "_" + xuhao);
            } else {
                error.add(file.getName() + "_" + xuhao);
                System.out.println("未找到匹配的合同记录");
            }

            conn.close();
        } catch (ClassNotFoundException e) {
            System.err.println("找不到JDBC驱动！请检查类路径。");
            e.printStackTrace();
        } catch (SQLException e) {
            System.err.println("数据库连接失败！");
            e.printStackTrace();
        }
    }


    private static void insertFileInfo(File file, String contractId) {
        String originalName = file.getName();
        String fileNameWithoutExt = originalName.substring(0, originalName.lastIndexOf("."));
        String fileExt = originalName.substring(originalName.lastIndexOf(".") + 1);
        long fileSize = file.length();

        // 生成新的文件路径（可根据实际需求调整）
        String timestamp = String.valueOf(System.currentTimeMillis());
        String newFileName = fileNameWithoutExt + "_" + timestamp + "." + fileExt;
        String filePath = "temp/" + newFileName;

        //将文件复制到目标路径
        FileUtil.copy(file, new File("D:\\document\\预算及项目全生命周期质控平台\\写入数据库合同\\" + newFileName), true);

        String insertSql = "INSERT INTO citic_file " +
                "(`id`, `create_by`, `create_time`, `update_by`, `update_time`, " +
                "`sys_org_code`, `data_type`, `data_id`, `file_name`, `file_ext`, " +
                "`file_size`, `file_path`, `file_type`) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(insertSql)) {

            // 设置参数
            pstmt.setString(1, generateId()); // 生成唯一ID
            pstmt.setString(2, "admin");
            pstmt.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
            pstmt.setNull(4, Types.VARCHAR); // update_by
            pstmt.setNull(5, Types.TIMESTAMP); // update_time
            pstmt.setString(6, "A02");
            pstmt.setString(7, "contract");
            pstmt.setString(8, contractId);
            pstmt.setString(9, originalName);
            pstmt.setString(10, fileExt);
            pstmt.setLong(11, fileSize);
            pstmt.setString(12, filePath);
            pstmt.setString(13, "合同");

            // 执行插入
            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                System.out.println("成功插入文件记录: " + originalName);

                // 这里可以添加实际文件复制到newFilePath位置的代码
                // FileUtil.copy(file, new File(newFilePath), true);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 生成唯一ID（根据你的实际需求调整）
    private static String generateId() {
        return String.valueOf(System.currentTimeMillis()) +
                String.valueOf((int) (Math.random() * 1000));
    }

}